package com.czk.server;

import com.czk.service.ExtServerService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

/**
 * netty的服务器
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/29 11:33
 */
public class NettyServer implements Callable<Channel> {
    private static Logger LOGGER = LoggerFactory.getLogger(NettyServer.class);
    private InetSocketAddress inetSocketAddress;
    private ExtServerService extServerService;

    public NettyServer(InetSocketAddress inetSocketAddress, ExtServerService extServerService) {
        this.inetSocketAddress = inetSocketAddress;
        this.extServerService = extServerService;
    }

    private final EventLoopGroup parentGroup = new NioEventLoopGroup();
    private final EventLoopGroup childGroup = new NioEventLoopGroup();
    private Channel channel;

    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(parentGroup, childGroup)
                    // 非阻塞模式
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new MyChannelInitializer(extServerService));

            channelFuture = b.bind(inetSocketAddress).syncUninterruptibly();
            this.channel = channelFuture.channel();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                LOGGER.info("服务端启动成功");
            } else {
                LOGGER.error("服务端启动失败");
            }
        }
        return channel;
    }

    public void destroy() {
        if (null == channel) return;
        channel.close();
        parentGroup.shutdownGracefully();
        childGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
}
